package com.his.his_system.common.filter;


import cn.hutool.json.JSONUtil;
import com.his.his_system.common.util.JwtUtil;
import com.his.his_system.common.util.RedisCache;
import com.his.his_system.common.util.ResultAdvice;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * token验证过滤器
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    /**
     * 抛出的异常可以被RestControllerAdvice捕获到
     */
    @Autowired
    @Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver resolver;


    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("Token");
        if (!StringUtils.hasText(token)) {
            System.out.println("没有token");
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        String userid = null;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        }catch (ExpiredJwtException e){
            response.setContentType("text/json;charset=utf-8");
            //塞到HttpServletResponse中返回给前台
            response.getWriter().write(JSONUtil.toJsonStr(ResultAdvice.fail("token过期，请重新登录", "503")));
            return;
        }
        catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token异常");
        }

//        if (System.currentTimeMillis() > JwtUtil.getExpirationTime(token)) {//已过期
//            response.setContentType("text/json;charset=utf-8");
//            //塞到HttpServletResponse中返回给前台
//
//            response.getWriter().write(JSONUtil.toJsonStr(ResultAdvice.fail("token过期，请重新登录", "503")));
//            return;
//        }


        //从redis中获取用户信息
        String redisKey = "login:" + userid;
        Object loginUser = redisCache.getCacheObject(redisKey);

        if (Objects.isNull(loginUser)) {
//            throw new TokenExpireException("token过期，请重新登录");

            response.setContentType("text/json;charset=utf-8");
            //塞到HttpServletResponse中返回给前台

            response.getWriter().write(JSONUtil.toJsonStr(ResultAdvice.fail("token过期，请重新登录", "503")));
            return;
        }

//        在这里赋权
        List<GrantedAuthority> auths =
                AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_" + "管理员");
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }
}